package com.millstein.tsinglog.service.impl;

import com.millstein.tsinglog.utils.IpUtils;
import com.millstein.tsinglog.utils.RequestUtils;
import com.millstein.tsinglog.model.pojo.User;
import com.millstein.tsinglog.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
@Slf4j
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendMail(String to, String subject, String content, User user) {

        log.info("用户[{} | {}] 发送邮件 - 到 {}", user.getUsername(),
                IpUtils.getRealIp(RequestUtils.getRequest()), to);
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(message);
            log.info("用户[{} | {}] 邮件发送成功！", user.getUsername(),
                    IpUtils.getRealIp(RequestUtils.getRequest()));
        } catch (MessagingException e) {
            log.error("用户[{} | {}] 发送邮件时发生异常！", user.getUsername(),
                    IpUtils.getRealIp(RequestUtils.getRequest()), e);
        }
    }
}
